<template>
  <view class="wrap">
    <view class="container" :style="{'margin': '0 '+mpWxPosition.bothSideMargin+'px'}">
      <view class="forms">
        <view class="avatar">
          <view class="avatar-show">
            <image :src="userInfo.showAvatar" mode="aspectFit"></image>
          </view>
          <button open-type="chooseAvatar" @chooseavatar="chooseAvatar">选择头像</button>
        </view>
        <view class="nickname-mobile">
          <view class="nickname">
            <view class="label">昵称</view>
            <input type="nickname" @change="onInputNickName" placeholder="请输入昵称" v-model="userInfo.showNickname"/>
          </view>
          <view class="mobile">
            <view class="label">手机号</view>
            <view class="show-button">
              <view class="mobile-show">{{ userInfo.showMobile }}</view>
              <button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
                <uv-icon name="reload" color="#2979ff" size="22"></uv-icon>
              </button>
            </view>
          </view>
        </view>
        <view class="buttons">
          <view class="reset-button">
            <uv-button type="warning" text="重置信息" @tap="showUserInfo"></uv-button>
          </view>
          <view class="save-button">
            <uv-button type="primary" text="保存以上信息" @tap="saveUserInfo"></uv-button>
          </view>
        </view>
      </view>
    </view>
    <view v-show="cropCanvas.isShow">
      <canvas canvas-id="myCanvas" :style="{'width': cropCanvas.width + 'px', 'height': cropCanvas.height + 'px'}"></canvas>
    </view>
  </view>
</template>

<script>
import { useMpWxPosition } from '@/stores/mpWxPosition'
import { useMpUser } from '@/stores/mpUser'
let _this;
export default {
  name: "User_center_Setting",
  beforeCreate() {
    _this = this;
  },
  data() {
    return {
      mpWxPosition: useMpWxPosition().getMpWxPosition,
      mpUser: useMpUser().getMpUser,
      userInfo: {
        showId: 0,
        showMobile: '',
        showNickname: '',
        showAvatar: ''
      },
      cropCanvas: {
        width: 100,
        height: 100,
        isShow: false
      }
    }
  },
  onLoad() {
    _this.showUserInfo()
  },
  methods: {
    saveUserInfo() {
      let doSave = (avatarBase64 = null) => {
        let postData = {
          nickname: _this.userInfo.showNickname
        }
        if (_this.userInfo.showMobile !== '手机号未设置') {
          postData['mobile'] = _this.userInfo.showMobile
        }
        if (avatarBase64) {
          postData['avatar'] = avatarBase64
        }
        _this.$api.post('/user/center/setting', postData).then(res => {
          uni.$uv.toast(res.message)
          useMpUser().updateMpUser(res.data.mpUser)
          _this.showUserInfo()
        })
      }
      if (useMpUser().mpUser.avatar !== _this.userInfo.showAvatar) {
        uni.getFileSystemManager().readFile({
          filePath: _this.userInfo.showAvatar,
          encoding: 'base64',
          success: (res) => {
            const base64Data = res.data;
            doSave(base64Data)
          },
          fail: (err) => {
            console.error('转换图片为Base64失败:', err);
          }
        })
      } else {
        doSave()
      }
    },
    showUserInfo() {
      let mpUser = useMpUser().getMpUser
      if (mpUser) {
        _this.userInfo.showId = Number(mpUser.id) + 31070
        _this.userInfo.showMobile = mpUser.mobile || '手机号未设置'
        _this.userInfo.showNickname = mpUser.nickname
        _this.userInfo.showAvatar = mpUser.avatar
      }
    },
    chooseAvatar(e) {
      _this.cropToSquare(e.detail.avatarUrl)
    },
    onInputNickName(e) {
      _this.userInfo.showNickname = e.detail.value
    },
    getPhoneNumber(e) {
      // 用户点击了获取手机号按钮
      if (e.detail.errMsg === 'getPhoneNumber:ok') {
        // 用户同意授权获取手机号
        _this.$api.post('/user/center/decrypt-mp-mobile', e.detail).then(res => {
          _this.userInfo.showMobile = res.data.mobile
        })
      } else {
        // 用户拒绝授权
      }
    },
    cropToSquare(tempFilePath) {
      // 获取图片信息，包括图片的宽度和高度
      uni.getImageInfo({
        src: tempFilePath,
        success: (imageInfo) => {
          const { width, height } = imageInfo;
          if (width === height) {
            _this.userInfo.showAvatar = tempFilePath;
          } else {
            // 计算正方形的边长
            const squareSide = Math.min(width, height);
            // 计算裁剪的起始坐标
            const x = (width - squareSide) / 2;
            const y = (height - squareSide) / 2;
            // 显示画布
            _this.cropCanvas.isShow = true;
            _this.cropCanvas.width = squareSide
            _this.cropCanvas.height = squareSide
            // 创建一个画布上下文
            const ctx = uni.createCanvasContext('myCanvas', _this);
            // 绘制图片到画布上
            ctx.drawImage(tempFilePath, x, y, squareSide, squareSide, 0, 0, squareSide, squareSide);
            // 将画布内容绘制到屏幕上
            ctx.draw(true, () => {
              // 绘制完成后，使用 uni.canvasToTempFilePath 输出裁剪后的图片
              uni.canvasToTempFilePath({
                canvasId: 'myCanvas',
                success: (res) => {
                  // 处理裁剪后的图片，例如保存或上传
                  _this.userInfo.showAvatar = res.tempFilePath
                  _this.cropCanvas.isShow = false;
                },
                fail: (err) => {
                  console.error('裁剪失败:', err);
                  _this.cropCanvas.isShow = false;
                }
              });
            });
          }
        },
        fail: (err) => {
          console.error('获取图片信息失败:', err);
          _this.cropCanvas.isShow = false;
        }
      });
    }
  }
}
</script>

<style lang="scss" scoped>
$avatarHeight: 100px;
$itemBorderColor: gray;
@mixin uLabel() {
  width: 60px;
  font-size: 15px;
  color: #3a3a3a;
}
.wrap {
  .container {
    .forms {
      margin-top: 10px;
      .avatar {
        border: 1px $itemBorderColor solid;
        border-radius: 4px;
        .avatar-show {
          display: block;
          margin: 10px auto;
          width: $avatarHeight;
          height: $avatarHeight;
          image {
            width: $avatarHeight;
            height: $avatarHeight;
          }
        }
        button {
          display: block;
          margin: 10px auto;
          font-size: 15px;
          width: 100px;
          height: 30px;
          line-height: 30px;
          text-align: center;
          background: #00B7FF;
          color: #fff;
          border-radius: 4px;
        }
      }
      .nickname-mobile {
        margin-top: 10px;
        border: 1px $itemBorderColor solid;
        border-radius: 4px;
        .nickname {
          margin: 10px;
          display: flex;
          .label {
            @include uLabel();
          }
        }
        .mobile {
          margin: 10px;
          display: flex;
          .label {
            @include uLabel();
          }
          .show-button {
            display: flex;
            justify-content: space-between;
            button {
              padding: 0;
              background: transparent;
              margin-left: 10px;
              &::after {
                border: none;
              }
            }
          }
        }
      }
      .buttons {
        .reset-button,.save-button {
          margin-top: 10px;
        }
      }
    }
  }
}
</style>
